package com.jt.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CGlibProxy {
    public static Object getProxy(Object target){
        //1.创建增强器对象
        Enhancer enhancer = new Enhancer();
        //2.设置父级.目标对象
        enhancer.setSuperclass(target.getClass());
        //3.定义回调方法，代理对象执行目标方法时调用
        enhancer.setCallback(getMethodInterceptor(target));
        //4.可以获取接口
        Class<?>[] interfaces = target.getClass().getInterfaces();
        enhancer.setInterfaces(interfaces);
        //5.创建代理对象
        return enhancer.create();
    }

    public static MethodInterceptor getMethodInterceptor(Object target){
        return new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                System.out.println("开启事务");
                Object result = method.invoke(target, args);
                System.out.println("关闭事务");
                return result;
            }
        };
    }
}
